package com.example.rabc.dao.impl;

import com.example.rabc.dao.PermissionDao;
import com.example.rabc.entity.Permission;
import com.example.rabc.config.DatabaseConnectionManager;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * PostgreSQL权限DAO实现类
 */
public class PostgreSqlPermissionDao implements PermissionDao {
    
    private final DatabaseConnectionManager connectionManager;
    
    public PostgreSqlPermissionDao() {
        this.connectionManager = DatabaseConnectionManager.getInstance();
    }
    
    @Override
    public Permission save(Permission entity) {
        String sql = "INSERT INTO permissions (permission_name, permission_code, resource_type, resource_path, parent_id, description, status, created_time, updated_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id";
        try (Connection conn = connectionManager.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            
            stmt.setString(1, entity.getPermissionName());
            stmt.setString(2, entity.getPermissionCode());
            stmt.setString(3, entity.getResourceType());
            stmt.setString(4, entity.getResourcePath());
            stmt.setLong(5, entity.getParentId());
            stmt.setString(6, entity.getDescription());
            stmt.setInt(7, entity.getStatus());
            stmt.setTimestamp(8, Timestamp.valueOf(entity.getCreatedTime()));
            stmt.setTimestamp(9, Timestamp.valueOf(entity.getUpdatedTime()));
            
            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    entity.setId(rs.getLong("id"));
                }
            }
            return entity;
        } catch (SQLException e) {
            throw new RuntimeException("保存权限失败", e);
        }
    }
    
    @Override
    public Permission update(Long id, Permission entity) {
        String sql = "UPDATE permissions SET permission_name=?, permission_code=?, resource_type=?, resource_path=?, parent_id=?, description=?, status=?, updated_time=? WHERE id=?";
        try (Connection conn = connectionManager.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            
            stmt.setString(1, entity.getPermissionName());
            stmt.setString(2, entity.getPermissionCode());
            stmt.setString(3, entity.getResourceType());
            stmt.setString(4, entity.getResourcePath());
            stmt.setLong(5, entity.getParentId());
            stmt.setString(6, entity.getDescription());
            stmt.setInt(7, entity.getStatus());
            stmt.setTimestamp(8, Timestamp.valueOf(entity.getUpdatedTime()));
            stmt.setLong(9, id);
            
            stmt.executeUpdate();
            entity.setId(id);
            return entity;
        } catch (SQLException e) {
            throw new RuntimeException("更新权限失败", e);
        }
    }
    
    @Override
    public void deleteById(Long id) {
        String sql = "DELETE FROM permissions WHERE id=?";
        try (Connection conn = connectionManager.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            
            stmt.setLong(1, id);
            stmt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException("删除权限失败", e);
        }
    }
    
    @Override
    public Optional<Permission> findById(Long id) {
        String sql = "SELECT * FROM permissions WHERE id=?";
        try (Connection conn = connectionManager.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            
            stmt.setLong(1, id);
            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    return Optional.of(mapRowToEntity(rs));
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException("查询权限失败", e);
        }
        return Optional.empty();
    }
    
    @Override
    public List<Permission> findAll() {
        String sql = "SELECT * FROM permissions";
        List<Permission> permissions = new ArrayList<>();
        try (Connection conn = connectionManager.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql);
             ResultSet rs = stmt.executeQuery()) {
            
            while (rs.next()) {
                permissions.add(mapRowToEntity(rs));
            }
        } catch (SQLException e) {
            throw new RuntimeException("查询所有权限失败", e);
        }
        return permissions;
    }
    
    @Override
    public List<Permission> findAll(int page, int size) {
        String sql = "SELECT * FROM permissions LIMIT ? OFFSET ?";
        List<Permission> permissions = new ArrayList<>();
        try (Connection conn = connectionManager.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            
            stmt.setInt(1, size);
            stmt.setInt(2, page * size);
            
            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    permissions.add(mapRowToEntity(rs));
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException("分页查询权限失败", e);
        }
        return permissions;
    }
    
    @Override
    public long count() {
        String sql = "SELECT COUNT(*) FROM permissions";
        try (Connection conn = connectionManager.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql);
             ResultSet rs = stmt.executeQuery()) {
            
            if (rs.next()) {
                return rs.getLong(1);
            }
        } catch (SQLException e) {
            throw new RuntimeException("统计权限数量失败", e);
        }
        return 0;
    }
    
    @Override
    public Optional<Permission> findByPermissionCode(String permissionCode) {
        String sql = "SELECT * FROM permissions WHERE permission_code=?";
        try (Connection conn = connectionManager.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            
            stmt.setString(1, permissionCode);
            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    return Optional.of(mapRowToEntity(rs));
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException("根据权限代码查询权限失败", e);
        }
        return Optional.empty();
    }
    
    @Override
    public List<Permission> findByResourceType(String resourceType) {
        String sql = "SELECT * FROM permissions WHERE resource_type=?";
        List<Permission> permissions = new ArrayList<>();
        try (Connection conn = connectionManager.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            
            stmt.setString(1, resourceType);
            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    permissions.add(mapRowToEntity(rs));
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException("根据资源类型查询权限失败", e);
        }
        return permissions;
    }
    
    @Override
    public List<Permission> findByParentId(Long parentId) {
        String sql = "SELECT * FROM permissions WHERE parent_id=?";
        List<Permission> permissions = new ArrayList<>();
        try (Connection conn = connectionManager.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            
            stmt.setLong(1, parentId);
            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    permissions.add(mapRowToEntity(rs));
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException("根据父ID查询权限失败", e);
        }
        return permissions;
    }
    
    @Override
    public List<Permission> findByStatus(Integer status) {
        String sql = "SELECT * FROM permissions WHERE status=?";
        List<Permission> permissions = new ArrayList<>();
        try (Connection conn = connectionManager.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            
            stmt.setInt(1, status);
            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    permissions.add(mapRowToEntity(rs));
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException("根据状态查询权限失败", e);
        }
        return permissions;
    }
    
    /**
     * 将ResultSet行映射为Permission实体
     * @param rs ResultSet
     * @return Permission实体
     * @throws SQLException SQL异常
     */
    private Permission mapRowToEntity(ResultSet rs) throws SQLException {
        Permission permission = new Permission();
        permission.setId(rs.getLong("id"));
        permission.setPermissionName(rs.getString("permission_name"));
        permission.setPermissionCode(rs.getString("permission_code"));
        permission.setResourceType(rs.getString("resource_type"));
        permission.setResourcePath(rs.getString("resource_path"));
        permission.setParentId(rs.getLong("parent_id"));
        permission.setDescription(rs.getString("description"));
        permission.setStatus(rs.getInt("status"));
        permission.setCreatedTime(rs.getTimestamp("created_time").toLocalDateTime());
        permission.setUpdatedTime(rs.getTimestamp("updated_time").toLocalDateTime());
        return permission;
    }
}